package com.freight.tws.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.freight.common.core.constant.HttpStatus;
import com.freight.common.core.constant.SecurityConstants;
import com.freight.common.core.constant.WebsocketConstants;
import com.freight.common.core.domain.R;
import com.freight.common.core.constant.DictConstants;
import com.freight.common.core.exception.ServiceException;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.core.web.domain.AjaxResult;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.system.api.RemoteUserService;
import com.freight.system.api.domain.SysUser;
import com.freight.tws.service.ITwsNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.freight.common.core.web.controller.BaseServiceImpl;
import com.freight.tws.mapper.TwsCompanyMapper;
import com.freight.tws.domain.TwsCompany;
import com.freight.tws.service.ITwsCompanyService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 货源方Service业务层处理
 *
 * @author wms
 * @date 2022-01-20
 */
@Service
public class TwsCompanyServiceImpl extends BaseServiceImpl<TwsCompanyMapper, TwsCompany> implements ITwsCompanyService {

    @Autowired
    private TwsCompanyMapper companyMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private ITwsNoticeService twsNoticeService;

    /**
     * 新增货源方
     * @param twsCompany
     * @return
     */
    @Override
    @Transactional
    public int add(TwsCompany twsCompany) {
        twsCompany.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        twsCompany.setCreateTime(new Date());
        twsCompany.setDelFlag(DictConstants.DELETE_BASE.OK.getKey());
        int insert = companyMapper.insert(twsCompany);
        // 修改系统用户昵称
        SysUser sysUser = new SysUser();
        sysUser.setUserId(twsCompany.getUserId());
        sysUser.setNickName(twsCompany.getCompanyName());
        sysUser.setTenantId(String.valueOf(twsCompany.getId()));
        remoteUserService.update(sysUser, SecurityConstants.INNER);
        // 保存到业务公告消息表（包含websocket通知）
        twsNoticeService.newTwsNotice("admin", WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY.getKey(), WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY.getName());
        return insert;
    }

    /**
     * 修改货源方
     * @param twsCompany
     * @return
     */
    @Override
    public int edit(TwsCompany twsCompany) {
        TwsCompany byId = companyMapper.selectById(twsCompany.getId());
        // 公司名变了，修改系统用户昵称
        if(StringUtils.isNotBlank(twsCompany.getCompanyName()) && !byId.getCompanyName().equals(twsCompany.getCompanyName())) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(byId.getUserId());
            sysUser.setNickName(twsCompany.getCompanyName());
            remoteUserService.update(sysUser, SecurityConstants.INNER);
        }
        // 如果审核状态是审核中，说明重新提交审核
        if(DictConstants.IS_CERT.SHZ.getKey().equals(twsCompany.getIsCert())) {
            // 保存到业务公告消息表（包含websocket通知）
            twsNoticeService.newTwsNotice("admin", WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY.getKey(), WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY.getName());
        }
        return companyMapper.updateById(twsCompany);
    }

    /**
     * 货源方审核
     * @param twsCompany
     * @return
     */
    @Override
    @Transactional
    public int cert(TwsCompany twsCompany) {
        TwsCompany byId = companyMapper.selectById(twsCompany.getId());
        // 如果状态不是在审核中
        if(!DictConstants.IS_CERT.SHZ.getKey().equals(byId.getIsCert())) {
            throw new ServiceException("审核失败");
        }
        String userName = this.getUserNameByCompanyId(byId.getId());
        // 审核通过
        if(DictConstants.IS_CERT.YRZ.getKey().equals(twsCompany.getIsCert())) {
            // 货源方角色的 roleId=100L
            Long[] longs = { 100L };
            R<Boolean> r = remoteUserService.insertAuthRole1(byId.getUserId(), longs, SecurityConstants.INNER);
            if (R.SUCCESS != r.getCode()) {
                throw new ServiceException(r.getMsg());
            }
            if(StringUtils.isNotBlank(userName)) {
                // 保存到业务公告消息表（包含websocket通知）
                twsNoticeService.newTwsNotice(userName, WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY_PASS.getKey(), WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY_PASS.getName());
            }
        } else if(DictConstants.IS_CERT.RZSB.getKey().equals(twsCompany.getIsCert())) {
            if(StringUtils.isNotBlank(userName)) {
                // 保存到业务公告消息表（包含websocket通知）
                twsNoticeService.newTwsNotice(userName, WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY_FAIL.getKey(), WebsocketConstants.TWS_NOTICE_TYPE.CERT_COMPANY_FAIL.getName());
            }
        }
        return companyMapper.updateById(twsCompany);
    }

    /**
     * 货源方禁/启用
     */
    @Override
    @Transactional
    public int stateChange(TwsCompany twsCompany) {
        TwsCompany byId = companyMapper.selectById(twsCompany.getId());
        if(byId.getState().equals(twsCompany.getState())) {
            throw new ServiceException("操作失败");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(byId.getUserId());
        if(DictConstants.COMMON_STATE.OK.getKey().equals(twsCompany.getState())) {
            sysUser.setStatus(DictConstants.USER_STATUS.OK.getKey());
        } else if(DictConstants.COMMON_STATE.NO.getKey().equals(twsCompany.getState())) {
            sysUser.setStatus(DictConstants.USER_STATUS.DISABLE.getKey());
        }
        AjaxResult ajaxResult = remoteUserService.changeStatus(sysUser, SecurityConstants.INNER);
        if(!ajaxResult.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)) {
            throw new ServiceException("操作失败1");
        }
        return companyMapper.updateById(twsCompany);
    }

    /**
     * 删除货源方
     */
    @Override
    @Transactional
    public int deletes(List<Long> asList) {
        List<TwsCompany> twsCompanies = companyMapper.selectBatchIds(asList);
        Long[] userIds = twsCompanies.stream().map(TwsCompany::getUserId).toArray(Long[]::new);
        AjaxResult ajaxResult = remoteUserService.deletes(userIds, SecurityConstants.INNER);
        if(!ajaxResult.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)) {
            throw new ServiceException("操作失败1");
        }
        return companyMapper.deleteBatchIds(asList);
    }

    /**
     * 查询物流公司的登录名
     * @return
     */
    @Override
    public String getUserNameByCompanyId(Long companyId) {
        TwsCompany company = companyMapper.selectById(companyId);
        if(StringUtils.isNotNull(company)) {
            // 查询用户信息
            R<SysUser> sysUserR = remoteUserService.infoById(company.getUserId(), SecurityConstants.INNER);
            if(sysUserR.getCode() == R.SUCCESS && StringUtils.isNotNull(sysUserR.getData())) {
                return sysUserR.getData().getUserName();
            }
        }
        return "";
    }

    @Override
    public TwsCompany getCompanyByUserId(Long billUserId) {
        TwsCompany twsCompany = companyMapper.selectByUserId(billUserId);
        return twsCompany;
    }

}
